const { DataTypes } = require('sequelize')
const sequelize = require('./db')

// 用户信息表
const User = sequelize.define(
  'User',
  {
    uuid: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV1,
      allowNull: false,
    },
    username: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    password: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    type: {
      type: DataTypes.ENUM('common', 'traffic', 'admin'),
      defaultValue: 'common',
      allowNull: false,
    },
    isOnline: {
      type: DataTypes.BOOLEAN,
      defaultValue: false,
      allowNull: false,
    },
    // 添加虚拟列
    isActive: {
      type: DataTypes.VIRTUAL,
      get() {
        return this.deletedAt ? 0 : 1 // 未删除为1，已删除为0
      },
    },
  },
  {
    paranoid: true, // 软删除
    indexes: [
      // 仅对未删除用户的用户名实施唯一性约束，允许已删除用户的用户名重复
      {
        name: 'username_active_unique',
        fields: [
          sequelize.literal('(CASE WHEN deletedAt IS NULL THEN username END)'),
        ],
        unique: true,
      },
    ],
  }
)

// 施工公告表（发布时间就用数据库中的create_at字段）
const Construction_Notice = sequelize.define(
  'Construction_Notice',
  {
    publishContent: {
      type: DataTypes.STRING,
      allowNull: false,
    },
  },
  {
    paranoid: true, // 软删除
  }
)

// 报告路况表
const Road_Condition_Report = sequelize.define(
  'Road_Condition_Report',
  {
    reportByWho: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    eventType: {
      type: DataTypes.ENUM(
        '碰撞',
        '刮擦',
        '翻车',
        '碾压',
        '刮蹭',
        '失火',
        '其他'
      ),
      allowNull: false,
    },
    eventAddress: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    nearbyBuilding: {
      type: DataTypes.STRING,
    },
    occurrenceTime: {
      type: DataTypes.DATE,
      allowNull: false,
    },
    eventDescription: {
      type: DataTypes.STRING,
    },
    eventPhoto: {
      type: DataTypes.STRING,
    },
    auditStatus: {
      type: DataTypes.ENUM('pending', 'approved', 'rejected'),
      defaultValue: 'pending',
      allowNull: false,
    },
  },
  {
    paranoid: true, // 软删除
  }
)

module.exports = {
  User,
  Construction_Notice,
  Road_Condition_Report,
}
